package com.prisetree.isv.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingtalk.isv.access.biz.prisetree.dao.OfficeResourcesImgMapper;
import com.dingtalk.isv.access.biz.prisetree.dao.OfficeResourcesMapper;
import com.dingtalk.isv.access.biz.prisetree.dao.OfficeResourcesRentMapper;
import com.dingtalk.isv.access.biz.prisetree.dao.SysDictDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.prisetree.isv.common.constant.SystemCode;
import com.prisetree.isv.common.controller.BaseController;
import com.prisetree.isv.domain.OfficeResources;
import com.prisetree.isv.domain.OfficeResourcesImg;
import com.prisetree.isv.domain.OfficeResourcesRent;
import com.prisetree.isv.domain.SysDict;
import com.prisetree.isv.domain.query.OfficeResourcesImgExample;
import com.prisetree.isv.domain.query.OfficeResourcesRentExample;
import com.prisetree.isv.request.parameter.FilterRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
@Transactional(readOnly = true)
public class OfficeResourcesService extends BaseController {
	
	@Autowired
	OfficeResourcesMapper officeResourcesMapper;
	@Autowired
	OfficeResourcesImgMapper officeResourcesImgMapper;
	@Autowired
	OfficeResourcesRentMapper officeResourcesRentMapper;
	@Autowired
	SysDictDao sysDictDao;
	
	public SystemCode otherFilterList() {
		List<String> list = sysDictDao.findOtherTag();
		SystemCode.SUCCESS.setResultObject(list);
		return SystemCode.SUCCESS;
	}
	
	public SystemCode cityTagList() {
		List<String> list = sysDictDao.findCityTag();
		SystemCode.SUCCESS.setResultObject(list);
		return SystemCode.SUCCESS;
	}
	
	public SystemCode fixedPriceTagList(String officeType) {
		List<SysDict> list = null;
		if(StringUtils.equals("2", officeType))
		{
			list = sysDictDao.findFixedPriceTag2();
		}
		else
		{
			list = sysDictDao.findFixedPriceTag();
		}
		SystemCode.SUCCESS.setResultObject(list);
		return SystemCode.SUCCESS;
	}
	
	public SystemCode flowPriceTagList() {
		List<SysDict> list = sysDictDao.findFlowPriceTag();
		SystemCode.SUCCESS.setResultObject(list);
		return SystemCode.SUCCESS;
	}
	
	public SystemCode officeTypeList() {
		List<SysDict> list = sysDictDao.findOfficeType();
		SystemCode.SUCCESS.setResultObject(list);
		return SystemCode.SUCCESS;
	}

	public SystemCode listByType(Integer pageNo, FilterRequest req) {
		Map<String, Object> param = new HashMap<String, Object>();
		// 房源类型房源类型(流动工位1,固定工位0)
		param.put("type", req.getType());
		// 场所类型(联合办公 0,园区 1,写字楼 2,不限-1)
		if (StringUtils.isNotEmpty(req.getOfficeType()) && !StringUtils.equals("-1", req.getOfficeType())) {
			param.put("officeType", req.getOfficeType().toString());
		}
		if (!StringUtils.equals(req.getCity(), "不限")) {
			param.put("city", req.getCity());
		}
		if (req.getStationNum() != null && req.getStationNum() != 0) {
			// 人数
			param.put("stationNum", req.getStationNum().toString());
		}
		if(StringUtils.isNotEmpty(req.getPayType()))
		{
			// 计费方式：0-每工位/天， 1-每工位/周， 2-每工位/月
			param.put("payType", req.getPayType());
		}
		if(StringUtils.isNotEmpty(req.getTerm()) && !"0".equals(req.getTerm()))
        {
            // 租期：月
            param.put("term", req.getTerm());
        }
		if(StringUtils.isEmpty(req.getPrice()) || "-1".equals(req.getPrice()))
		{
			if(req.getPriceFrom() == null)
			{
				// 空相当于0
				req.setPriceFrom("0");
			}
			if(req.getPriceTo() == null)
			{
				// 空相当于无限大
				req.setPriceTo("10000000");
			}
		}
		else
		{
			String[] prices = req.getPrice().split("-");
			if(prices.length == 2)
			{
				req.setPriceFrom(prices[0]);
				req.setPriceTo(prices[1]);
			}
		}
		if(Double.valueOf(req.getPriceFrom()) > Double.valueOf(req.getPriceTo()))
		{
			// 起始价格不能大于结束价格
			return SystemCode.PRICE_PARAM_ERROR;
		}
		// 价格限制
		param.put("priceFrom", req.getPriceFrom().toString());
		param.put("priceTo", req.getPriceTo().toString());
		// 工位类型：(独立办公区0,开放办公区1,不限-1)
		if(Integer.valueOf(req.getStationType()) != -1)
		{
			param.put("stationType", req.getStationType().toString());
		}
		// 标签
		if ((req.getOther() != null) && (req.getOther().length() > 0)) {
			List<String> tagList = new ArrayList<String>();
			for (String s : req.getOther().split(",")) {
				tagList.add("%" + s + "%");
			}
			param.put("tagList", tagList);
		}
		System.out.println(req.getOther());
		PageHelper.startPage(pageNo, 10);
		List<OfficeResources> list = officeResourcesMapper.selectByParam(param);
		if (list != null && list.size() > 0) {
			for (OfficeResources resources : list) {
				if ((req.getLon() != null) && (req.getLat() != null)) {
					double radLat1 = Double.valueOf(req.getLat()) * Math.PI / 180.0;
					double radLat2 = Double.valueOf(resources.getLat()) * Math.PI / 180.0;
					double radLon1 = Double.valueOf(req.getLon()) * Math.PI / 180.0;
					double radLon2 = Double.valueOf(resources.getLon()) * Math.PI / 180.0;
					double a = radLat1 - radLat2;
					double b = radLon1 - radLon2;
					double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
					s = Math.round(s * 6378.137 * 10000) / 10000;
					//距离(单位:千米)
					resources.setDistance(s + "");
				} else {
					return SystemCode.LATLON_NOTFOUND;
				}
			}
		}
		Collections.sort(list, new Comparator<OfficeResources>() {
            @Override
            public int compare(OfficeResources o1, OfficeResources o2) {
                Double d1 = Double.valueOf(o1.getDistance());  
                Double d2 = Double.valueOf(o2.getDistance());  
                return d1.compareTo(d2); 
            }
        });
		JSONArray arr = new JSONArray();
//		PageableDataVO<OfficeResources> pageList = this.setPageableData(dataTableVO, list);
		PageInfo<OfficeResources> page = new PageInfo<OfficeResources>(list);
		if (list != null && list.size() > 0) {
			for (OfficeResources resources : (List<OfficeResources>)page.getList()) {
				JSONObject jsub = new JSONObject();
//				if ((StringUtils.equals(req.getCity(), "附近")) && (Double.valueOf(resources.getDistance()) > 5)) {
//					continue;
//				}
				jsub.put("id", resources.getId());
				jsub.put("name", resources.getName());
				jsub.put("stationNum", resources.getStationNum());
				jsub.put("starNum", resources.getStarNum());
				jsub.put("minTime", resources.getMinTime());
				jsub.put("distance", resources.getDistance());
				jsub.put("addr", resources.getDetailAddr());
				jsub.put("imgUrl", resources.getImgUrl());
				jsub.put("minRentTime", resources.getMinRentTime());
                jsub.put("minRentTimeType", resources.getMinRentTimeType());
				// 如果是按工位人数出租
				if("0".equals(resources.getRentType()))
                {
                    jsub.put("minRentPrice", resources.getMinRentPrice());
                }
                // 如果按照面积出租
                else if("1".equals(resources.getRentType())) {
                    jsub.put("minRentPrice", resources.getUnitPrice());
                    jsub.put("officeArea", resources.getOfficeArea());
                    jsub.put("usageRate", resources.getUsageRate());
                }

				arr.add(jsub);
			}
		}
		
		JSONObject json = new JSONObject();
		json.put("resourcesList", arr);
		json.put("hasNext", page.isHasNextPage());
		json.put("allPageNo", page.getTotal()+1);
		SystemCode.SUCCESS.setResultObject(json);
		return SystemCode.SUCCESS;
	}

	public SystemCode detail(String id, Integer stationAttr) {
		OfficeResources officeResources = officeResourcesMapper.selectByPrimaryKey(id);
		if (officeResources == null) {
			return SystemCode.OFFICERESOURCES_NOTFOUND;
		} else {
			OfficeResourcesRentExample rentExample = new OfficeResourcesRentExample();
			if (stationAttr != 2) {
				//流动、固定
				rentExample.setOrderByClause("station_allnum ASC");
				rentExample.createCriteria().andParentIdEqualTo(id).andStationAttrEqualTo(stationAttr);
			} else {
				//写字楼
				rentExample.createCriteria().andParentIdEqualTo(id).andRentTypeEqualTo(1);
			}
			List<OfficeResourcesRent> rentList = officeResourcesRentMapper.selectByExample(rentExample);
			
			OfficeResourcesImgExample imgExample = new OfficeResourcesImgExample();
			imgExample.createCriteria().andOfficeResourcesIdEqualTo(id);
			List<OfficeResourcesImg> imgList = officeResourcesImgMapper.selectByExample(imgExample);
			JSONObject json = new JSONObject();
			json.put("id", id);
			json.put("name", officeResources.getName());
			json.put("officeMobile", officeResources.getContactMobile());
			json.put("stationNum", officeResources.getStationNum());
			JSONArray imgArr = new JSONArray();
			JSONArray rentSpecializedArr = new JSONArray();
			Integer openPrice = 10000;
			Integer specializedPrice = 10000;
			Integer stationSurplusNum = 0;

			if (rentList != null && rentList.size() > 0) {
				if (stationAttr != 2) {
					//流动、固定
					for (OfficeResourcesRent rent : rentList) {
						stationSurplusNum = stationSurplusNum + rent.getSurplusNum();
						if (rent.getStationType() == 0) {
							//独立办公室
							if (rent.getStaitonPrice() < specializedPrice) {
								specializedPrice = rent.getStaitonPrice();
								json.put("specializedPriceUnit", rent.getBillingMode());
							}
							rentSpecializedArr.add(rent);
						} else if (rent.getStationType() == 1){
							//开放办公室
							if (rent.getStaitonPrice() < openPrice) {
								openPrice = rent.getStaitonPrice();
								json.put("openPriceUnit", rent.getBillingMode());
								json.put("rentOpen", rent);
							}
						}
					}
				} else {
					//写字楼
					json.put("rentArea", rentList.get(0));
				}
			}
			json.put("surplusNumAll", stationSurplusNum);
			json.put("openPrice", openPrice);
			json.put("specializedPrice", specializedPrice);
			json.put("rentSpecializedList", rentSpecializedArr);
			
			if (imgList != null && imgList.size() > 0) {
				for (OfficeResourcesImg img : imgList) {
					if (img.getIsHeader() == 1) {
						JSONObject jsub = new JSONObject();
						jsub.put("imgId",img.getId());
						jsub.put("imgUrl", img.getImgUrl());
						imgArr.add(jsub);
					} 
//					else if(img.getIsHeader() == 3) {
//						json.put("geographyImg", img.getImgUrl());
//					}
				}
			}
			json.put("imgList", imgArr);
			
			String orgStr = officeResources.getFeature();
			if (orgStr.length() > 0) {
//		        String[] strList = orgStr.split(",");
				json.put("feature", officeResources.getFeature());
			}
			json.put("baseService", officeResources.getBaseService());//基础服务
			json.put("baseFacility", officeResources.getBaseFacility());//基础设施
			json.put("speService", officeResources.getSpeService());//特色服务
			json.put("traffic", officeResources.getTraffic());
			json.put("nearby", officeResources.getNearby());
			json.put("addr", officeResources.getProvince() + officeResources.getCity() + officeResources.getArea() + officeResources.getDetailAddr());
			json.put("lon", officeResources.getLon());
			json.put("lat", officeResources.getLat());
			SystemCode.SUCCESS.setResultObject(json);
			return SystemCode.SUCCESS;
		}
	}

}
